import React from 'react';
import copy from 'copy-to-clipboard';
import {connect} from 'dva';
import {createForm} from 'rc-form';
import moment from 'moment';
import {
  Tabs,
  WhiteSpace,
  WingBlank,
  List,
  Button,
  Icon,
  Popup,
  Tag,
  Toast,
  ListView,
  Popover,
  InputItem,
} from 'antd-mobile';
import VipInfoRemarksPage from './VipInfoRemarksPage';
import Container from '../components/Base/Container';
import VipListShow from '../components/Base/VipInfoShow';
import VipShopShow from '../components/Base/VipShopShow';
import VisitFunction from '../components/Base/VisitFunction';
import VisitedRecord from '../components/Base/VisitedRecord';
import { routerRedux } from 'dva/router';
import { CouponList, CouponCodeList } from '../components/Base/CouponCode';
import styles from './PrecisionPage1_info.css';

const Item = List.Item;
const TabPane = Tabs.TabPane;

const isIPhone = new RegExp('\\biPhone\\b|\\biPod\\b', 'i').test(window.navigator.userAgent);
let maskProps;
if (isIPhone) {
  // Note: the popup content will not scroll.
  maskProps = {
    onTouchStart: e => e.preventDefault(),
  };
}

class P extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      value: 0,
      value2: 0,
      value3: 0,
      value4: 0,
      visible: false,
      clicked: 'none',
      clicked1: 'none',
      clicked2: 'none',
      smstext: '',
      remarks: '',
    };
  }
  componentDidMount() {
    this.props.fetchVisitedRecord();
    this.props.fetchVipInfo();
    this.props.fetchVipConsume();
    this.props.fetchVipRecommend();

    const {currentUser,cardNo}=this.props;
    this.props.fetchVipAcc(currentUser.shopId,cardNo);

    window.scrollTo(0,0)
  }
  onCopy = (e) => {
    copy(e.target.parentElement.parentElement.getElementsByTagName('p')[0].innerText);
    Toast.info('复制成功', 1);
  };
  onClose = () => {
    Popup.hide();
  };
  replaceVipInfo = (text) => {
    let i = 0;
    text = '您好！我是[]店铺的客户专员[]。您上次在我们店买的[],宝宝用得怎么样啦？';
    const { branchName, saleManName } = this.props.currentUser;
    const v = [null, branchName, saleManName, this.props.vipConsume[0] ? this.props.vipConsume[0].item_name : ''];
    return text.replace(/（系统自动调取）/ig, '').replace(/(\[\])/ig, (a, b, c) => {
      i += 1;
      return `【${v[i]}】`;
    });
  };

  sendWX = (boolean) => {
    this.setState({
      visible: boolean,
    });
  };

  onClick1 = (item) => {
    Popup.show(<div>
      <List
        renderHeader={item => (
          <div style={{ position: 'relative' }}>
              话术
              <span
                style={{
                  position: 'absolute', right: 3, top: -5,
                }}
                onClick={() => this.onClose('cancel')}
              >
                <Icon type="cross" />
              </span>
          </div>)}
      >
        <div style={{ maxHeight: '400px', overflowY: 'auto' }}>
          <List.Item wrap>
            <Tag selected>拉近关系</Tag>
            <Button style={{ float: 'right' }} size="small" onClick={e => this.onCopy(e)}>复制</Button>
            <p>{this.replaceVipInfo(item.closerRelation)}</p>
          </List.Item>
          <List.Item wrap>
            <Tag selected>育儿知识</Tag>
            <Button style={{ float: 'right' }} size="small" onClick={e => this.onCopy(e)}>复制</Button>
            <p> {item.parentingKnowledge}</p>
          </List.Item>
          <List.Item wrap>
            <Tag selected>产品推荐</Tag>
            <Button style={{ float: 'right' }} size="small" onClick={e => this.onCopy(e)}>复制</Button>
            <p>{item.recommendTalk}</p>
          </List.Item>
          <List.Item wrap>
            <Tag selected>结束语</Tag>
            <Button style={{ float: 'right' }} size="small" onClick={e => this.onCopy(e)}>复制</Button>
            <p>{item.closeTalk}</p>
          </List.Item>
        </div>

      </List>
    </div>,
      { animationType: 'slide-up', maskProps, maskClosable: false });
  };
  onChange = (key) => {

  };
  getAge = (birthday) => {
    const months = moment().diff(moment(birthday), 'months');
    const years = Math.floor(months / 12);
    if (months >= 0) {
      return years > 0 ? `${years}岁${months % 12}个月` : `${months % 12}个月`;
    }
    return `孕前${months?Math.abs(months % 12):'  '}个月`;
  };

  getDateString = (birthday) => {
    if (birthday) {
      return moment(birthday).subtract(8, 'hours').format('YYYY-MM-DD');
    }
    return '';
  };

  getVipType = (type) => {
    switch (type) {
      case 'A':
        return '核心会员';
      case 'B':
        return '忠诚会员';
      case 'C':
        return '普通会员';
      case 'D':
        return '低效会员';
      case 'E':
        return '流失会员';
      case 'F':
        return '新注册会员';
      default:

    }
  };

  renderRow = (rowData, a, index) => {
    return (
      <Item
        key={rowData._id}
        extra={<Button
          onClick={() => {
            this.onClick1(rowData);
          }
          } size="small" inline
        >话术</Button>
       }
      >
        {rowData.goodsRecommend} <span style={{ color: '#888888', fontSize: '12px' }}>({rowData.goodsSpec})</span>
      </Item>
    );
  }

  hasMore = () => {
    return this.props.recommend && this.state.recommendData && this.props.recommend.length > this.state.recommendData.length;
  }

  fetchMoreRecommend = () => {
    this.setState({ recommendData: this.props.recommend });
  }


  onRemarksSave = (e) => {
    // Popup.hide();
  }

  onRemarksClick = () => {
    const { saveRemarks, vipInfo } = this.props;
    Popup.show(<VipInfoRemarksPage
      onSave={(text) => {
        saveRemarks(vipInfo._id, text);
        Popup.hide();
      }}
      value={vipInfo.remarks}
    />,
      { animationType: 'slide-up', maskClosable: false });
  };

  getShopNum=(vipItem)=>{
    let num=0
    vipItem.forEach(item=>{
      num+=item.sale_qnty
    })
    return num;
  }

  hideShare = () => {
    this.setState({
      visible: false,
    });
  }

  render() {
    const {getFieldProps} = this.props.form;
    const dataSource = new ListView.DataSource({
      rowHasChanged: (row1, row2) => row1 !== row2,
    });

    const {vipInfo, tasks2, vipConsume, currentUser,vipInfoAcc, recommend} = this.props;
    const {recommendData} = this.state;

    return (
      <Container title="会员详情" navOption={{
        rightContent: <Popover
          mask
          transitionName="fade"
          overlayClassName="fortest"
          overlayStyle={{ color: 'currentColor' }}
          visible={false}
          overlay={[
            (<Item key="4" value="scan">点击右上角，分享给朋友</Item>),
          ]}
          align={{
            offset: [-200, -200],
            targetOffset: ['30%', '40%'],
          }}
          onVisibleChange={(e)=>{this.sendWX(e)}}
          onSelect={()=>{alert('this.onSelect')}}
        >
          <span />
        </Popover>,
      }}>

{this.state.visible &&
        <div className={styles["shareFunction"]} onClick={this.hideShare}>
          <span className={styles["sftt"]}>点击右上角，分享给朋友</span>
        </div>
 }

        <VipListShow rowData={vipInfo}
                     vipInfoAcc={vipInfoAcc}
                     onRemarksClick={this.onRemarksClick}
                     onLabelClick={this.props.onLabelClick}
        />

        <Tabs defaultActiveKey="2" onChange={this.onChange} swipeable={false}>
          <TabPane tab="回访记录" key="1">
            <VisitedRecord/>
          </TabPane>
          <TabPane tab="消费记录" key="2">
            <VipShopShow vipConsume={vipConsume}/>
          </TabPane>
          <TabPane tab="商品推荐" key="3">
            <List
              renderHeader={() => `共 ${this.props.recommend.length} 条`}
              renderFooter={() => {/* <div style={{ padding: 30, textAlign: 'center' }} onClick={() => { this.fetchMoreRecommend(); }}>
               {!this.hasMore() ? '已全部加载完' : this.props.isLoading ? '加载中...' : '更多'}
               </div>*/
              }
              }
            >
              {this.props.recommend && this.props.recommend.map((item) => {
                return (
                  <Item key={item._id} extra={<Button onClick={() => {
                    this.onClick1(item);
                  }} size="small" inline>话术</Button>}>
                    {item.goodsRecommend} <span style={{color: '#888888', fontSize: '12px'}}>({item.goodsSpec})</span>
                  </Item>
                );
              })}
            </List>
          </TabPane>
          <TabPane tab="优惠券" key="4">
            <CouponCodeList couponList={this.props.couponList} couponCodeList={this.props.couponCodeList} />
          </TabPane>
          <TabPane tab="我要发券" key="5">
            <CouponList
              user={this.props.currentUser}
              onSend={this.props.sendCoupon}
              couponList={this.props.couponList}
              couponCodeList={this.props.couponCodeList}
            />
          </TabPane>
         {/* <TabPane tab="回访记录" key="4">
            <div>
              <ListView
                dataSource={dataSource.cloneWithRows(tasks2)}
                renderHeader={() => <span>共 {tasks2.length} 人</span>}
                renderRow={this.renderRow}
                pageSize={20}
                initialListSize={20}
                // scrollRenderAheadDistance={500}
                scrollEventThrottle={20}
                // onEndReached={this.onEndReached}
                // onEndReachedThreshold={10}
                useBodyScroll
              />
            </div>
          </TabPane>*/}
          {/* <TabPane tab="优惠券" key="4">
           <div>
           <List renderHeader={() => '共 20 条'}>
           {data.map(i => (
           <RadioItem
           key={i.value}
           checked={value === i.value} onChange={() => this.onChange(i.value)}
           >
           <div className={styles.card} />
           </RadioItem>
           ))}
           </List>
           </div>
           </TabPane>*/}
        </Tabs>
        <WhiteSpace />
        <VisitFunction
          sendWX={this.sendWX}
          location={this.props.location}
          noResult={true}
        />
      </Container>
    );
  }
}
export default connect((state, props) => {
  return {
    couponList: state.coupon.couponList,
    couponCodeList: state.coupon.codeList,
    currentUser: state.auth.currentUser,
    cardNo: props.location.query.cardNo,
    vipInfo: state.task.vipInfo,
    vipInfoAcc: state.task.vipInfoAcc,
    vipConsume: state.task.vipConsume,
    recommend: state.task.recommend,
    tasks2: state.task.tasks2,
  };
}, (dispatch, props) => {
  return {
    fetchVisitedRecord(){
      const cardNo = props.location.query.cardNo;
      dispatch({
        type: 'task/fetchVisitedRecord',
        payload: { cardNo },
      });
    },
    fetchVipInfo() {
      const card_id = props.location.query.cardId;
      dispatch({
        type: 'task/fetchVipInfo',
        payload: { card_id },
      });
    },
    fetchVipConsume() {
      const card_id = props.location.query.cardId || props.location.query.cardNo;
      dispatch({
        type: 'task/fetchVipConsume',
        payload: { card_id },
      });
    },
    fetchVipRecommend() {
      const { taskType, cardNo: card_no } = props.location.query;
      dispatch({
        type: 'task/fetchRecommend',
        payload: { taskType, card_no },
      });
    },
    saveRemarks(_id, remarks) {
      const { cardNo } = props.location.query;
      dispatch({
        type: 'vip/updateRemarks',
        payload: { _id, cardNo, remarks },
      });
    },
    fetchVipAcc(shopId,cardNo){
      dispatch({
        type: 'task/fetchVipAcc',
        payload: { shopId, cardNo },
      });
    },
    onLabelClick(){
      dispatch( routerRedux.push(`/labelEdit?cardNo=${props.location.query.cardNo}`) );
    },
    sendCoupon(coupon) {
      const cardNo = props.location.query.cardNo;
      dispatch({
        type: 'coupon/sendCoupon',
        payload: { coupon, card_id: cardNo },
      });
    },
  };
})(createForm()(P));
